package com.shijimo.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shijimo.server.domain.Teacher;
import com.shijimo.server.domain.TeacherExample;
import com.shijimo.server.dto.PageDto;
import com.shijimo.server.dto.TeacherDto;
import com.shijimo.server.mapper.TeacherMapper;
import com.shijimo.server.util.CopyUtil;
import com.shijimo.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Dream_飞翔
 * @email 1072876976@qq.com
 */

@Service
public class TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    /**
     * 查询列表方法
     *
     * @param pageDto 分页对象
     */
    public void list(PageDto pageDto) {
        // 开启mybatis分页，pageNum从1开始
        // 生效的位置是开启分页后下方的第一个select语句
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());

        TeacherExample teacherExample = new TeacherExample();


        // 进行查询
        List<Teacher> teacherList = teacherMapper.selectByExample(teacherExample);

        PageInfo<Teacher> pageInfo = new PageInfo<>(teacherList);
        // 查询到的总条数
        pageDto.setTotal(pageInfo.getTotal());

        List<TeacherDto> teacherDtoList = CopyUtil.copyList(teacherList, TeacherDto.class);
        // 设置最终的查询结果
        pageDto.setList(teacherDtoList);
    }

    /**
     * 保存修改结果
     * 1. 如果从前端传来的对象中Id有值的话就是更新操作
     * 2. 如果Id为空则说明是进行新增操作
     *
     * @param teacherDto
     */
    public void save(TeacherDto teacherDto) {
        Teacher teacher = CopyUtil.copy(teacherDto, Teacher.class);
        // 判断Id是否有值
        if (StringUtils.isEmpty(teacherDto.getId())) {
            this.insert(teacher);
        } else {
            this.update(teacher);
        }
    }

    /**
     * 添加方法
     */
    private void insert(Teacher teacher) {
        // 设置Id
        teacher.setId(UuidUtil.getShortUuid());
        teacherMapper.insert(teacher);
    }

    /**
     * 更新方法
     */
    private void update(Teacher teacher) {

        teacherMapper.updateByPrimaryKey(teacher);
    }

    /**
     * 删除方法
     */
    public void delete(String id) {
        teacherMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询所有讲师
     *
     * @return 所有讲师集合
     */
    public List<TeacherDto> all() {
        TeacherExample teacherExample = new TeacherExample();
        // 进行查询，查询到所有的数据
        List<Teacher> teacherList = teacherMapper.selectByExample(teacherExample);
        // 转成Dto并返回
        return CopyUtil.copyList(teacherList, TeacherDto.class);
    }

}
